package cn.fanxin.utils;

import cn.fanxin.tools.MyException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：china-fanxin
 * @Website: https://fan-xin.cn
 * @Date 2023/3/3 13:34
 * @Description:
 */
public class ShellUtils {


    /**
     * @Author: china-fanxin
     * @Website: https://fan-xin.cn
     * @Description: 调用shell命令
     * @Date 2023/3/3 13:36
     * @Param: [shellString]
     * @Return: void
     */
    public static void callShellByExec(String shellString) {
        BufferedReader reader = null;
        try {
            String[] command = new String[]{"/bin/sh","-c",shellString};
            Process process = Runtime.getRuntime().exec(command);
            int exitValue = process.waitFor();
//            if (0 != exitValue) {
//                throw new MyException("call shell failed. error code is :" + exitValue);
//            }
            // 返回值
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.destroy();
        } catch (Throwable e) {
            throw new MyException("call shell failed. " + e);
        }
    }

    /**
     * @Author: china-fanxin
     * @Website: https://fan-xin.cn
     * @Description: 调用shell命令,并接受返回内容到列表
     * @Date 2023/4/5 19:17
     * @Param: [shellString]
     * @Return: java.util.List<java.lang.String>
     */
    public static List<String> callShellByExecAndReturnUpper(String shellString) {
        List<String> res = new ArrayList<>();
        BufferedReader reader = null;
        try {
            String[] command = new String[]{"/bin/sh","-c",shellString};
            Process process = Runtime.getRuntime().exec(command);
            int exitValue = process.waitFor();
//            if (0 != exitValue) {
//                throw new MyException("call shell failed. error code is :" + exitValue);
//            }
            // 返回值
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                res.add(line.trim().toUpperCase());
            }
            process.destroy();
        } catch (Throwable e) {
            throw new MyException("call shell failed. " + e);
        }
        return res;
    }

}
